package io.terminus.paas.profiler.model

import com.alibaba.dubbo.common.Constants
import com.alibaba.dubbo.common.URL
import com.alibaba.dubbo.common.utils.StringUtils

/**
 * Created by gengrong on 16/3/18.
 */
class Configuration() {

    var id: Long? = null

    var service: String? = null

    var params: String? = null

    val parameters = hashMapOf<String, String>();

    var application: String? = null

    var address: String? = null

    var username: String? = null

    var enabled: Boolean = false

    fun toUrl(): URL {
        var group: String? = null
        var version: String? = null
        var path = service!!
        var i = path.indexOf("/")
        if (i > 0) {
            group = path.substring(0, i)
            path = path.substring(i + 1)
        }
        i = path.lastIndexOf(":")
        if (i > 0) {
            version = path.substring(i + 1)
            path = path.substring(0, i)
        }
        val sb = StringBuilder()
        sb.append(Constants.OVERRIDE_PROTOCOL)
        sb.append("://")
        if (!StringUtils.isBlank(address) && Constants.ANY_VALUE != address) {
            sb.append(address)
        } else {
            sb.append(Constants.ANYHOST_VALUE)
        }
        sb.append("/")
        sb.append(path)
        sb.append("?")
        val param = StringUtils.parseQueryString(params)
        param.putAll(parameters);
        param.put(Constants.CATEGORY_KEY, Constants.CONFIGURATORS_CATEGORY)
        param.put(Constants.ENABLED_KEY, enabled.toString())
        param.put(Constants.DYNAMIC_KEY, "false")
        if (!StringUtils.isBlank(application) && Constants.ANY_VALUE != application) {
            param.put(Constants.APPLICATION_KEY, application)
        }
        if (group != null) {
            param.put(Constants.GROUP_KEY, group)
        }
        if (version != null) {
            param.put(Constants.VERSION_KEY, version)
        }
        sb.append(StringUtils.toQueryString(param))
        return URL.valueOf(sb.toString())
    }
}